package cn.lqz.bucttrain.service.impl;

import cn.lqz.bucttrain.enums.ResponseCodeEnum;
import cn.lqz.bucttrain.enums.UserStatusEnum;
import cn.lqz.bucttrain.exceptions.BaseException;
import cn.lqz.bucttrain.mapper.OrderMapper;
import cn.lqz.bucttrain.mapper.PassengerMapper;
import cn.lqz.bucttrain.mapper.UserMapper;
import cn.lqz.bucttrain.pojo.dto.PassengerPageQueryDTO;
import cn.lqz.bucttrain.pojo.entity.Passenger;
import cn.lqz.bucttrain.pojo.entity.User;
import cn.lqz.bucttrain.pojo.vo.PageResultVO;
import cn.lqz.bucttrain.service.PassengerService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.List;

/**
 * 乘客Service
 */
@Service
@Slf4j
public class PassengerServiceImpl implements PassengerService {
    @Resource
    private PassengerMapper passengerMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private OrderMapper orderMapper;

    /**
     * 加载或查询
     * @param passengerPageQueryDTO
     * @return
     */
    @Override
    public PageResultVO loadPassengerList(PassengerPageQueryDTO passengerPageQueryDTO) {
        log.info("加载或查询乘客列表：{}",passengerPageQueryDTO);
        PageHelper.startPage(passengerPageQueryDTO.getPageNo(),passengerPageQueryDTO.getPageSize());
        Page<Passenger> page = passengerMapper.findBatch(passengerPageQueryDTO);
        return new PageResultVO(passengerPageQueryDTO.getPageNo(),passengerPageQueryDTO.getPageSize(),page.getTotal(),page.getResult());
    }

    /**
     * 添加或修改
     * @param passenger
     */
    @Override
    public void addOrUpdatePassenger(Passenger passenger) {
        log.info("添加或修改乘客：{}",passenger);
        // 要绑定的用户不存在
        User existUser = userMapper.findByUserId(passenger.getUserId());
        if (null==existUser){
            throw new BaseException(ResponseCodeEnum.CODE_400.getCode(),"要绑定的用户不存在");
        }
        // 要绑定的用户已被禁用
        if(UserStatusEnum.DISABLE.getStatus().equals(existUser.getStatus())){
            throw new BaseException(ResponseCodeEnum.CODE_400.getCode(),"要绑定的用户已被禁用");
        }
        Passenger existPassengerWithUser = passengerMapper.findByPhoneNumberAndUserId(passenger.getPhoneNumber(),passenger.getUserId());
        // 新增
        if (passenger.getPassengerId()==null){
            if (existPassengerWithUser!=null){
                throw new BaseException(ResponseCodeEnum.CODE_400.getCode(),"用户已绑定该乘客电话");
            }
            passengerMapper.insert(passenger);
        }else{ // 修改
            Passenger existPassenger = passengerMapper.findByPassengerId(passenger.getPassengerId());
            // 要修改的乘客不存在
            if (null==existPassenger){
                throw new BaseException(ResponseCodeEnum.CODE_600);
            }
            // 要修改成的电话号码已经被绑定
            if (existPassengerWithUser!=null && !existPassengerWithUser.getPassengerId().equals(existPassenger.getPassengerId())){
                throw new BaseException(ResponseCodeEnum.CODE_400.getCode(),"用户已绑定该乘客电话");
            }
            // 订单表关联的是乘客id，因此无需修改订单表
            passengerMapper.update(passenger);
        }
    }

    /**
     * 删除乘客
     * @param passengerId
     */
    @Override
    public void deletePassenger(Long passengerId) {
        log.info("删除乘客：passengerId={}",passengerId);
        passengerMapper.delete(passengerId);
    }

    /**
     * 导出乘客excel表
     * @param passengerList
     * @param response
     */
    @Override
    public void exportPassengerExcel(List<Passenger> passengerList, HttpServletResponse response) {
        log.info("乘客：导出excel表");
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/乘客报表.xlsx");
        try{
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            for(int i=1;i<=passengerList.size();i++){
                XSSFRow xssfRow = sheet.createRow(i);
                for(int j=0;j<6;j++){
                    xssfRow.createCell(j);
                }
            }
            for(int i=0;i<passengerList.size();i++){
                Passenger passenger = passengerList.get(i);
                XSSFRow row = sheet.getRow(i + 1);
                row.getCell(0).setCellValue(passenger.getPassengerId());
                row.getCell(1).setCellValue(passenger.getName());
                row.getCell(2).setCellValue(passenger.getPhoneNumber());
                row.getCell(3).setCellValue(passenger.getIdCard());
                row.getCell(4).setCellValue(passenger.getAge());
                row.getCell(5).setCellValue(passenger.getUserId());
            }
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            excel.close();
            inputStream.close();
        }catch (Exception e){
            log.error("订单导出excel表异常",e);
            throw new BaseException(ResponseCodeEnum.CODE_500);

        }
    }
}
